package com.yunmang.activity.daohuo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yunmang.DaoUtils.CommonDaoUtils;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.activity.exception.LeakageInformation;
import com.yunmang.adapter.ConfirmAdapter;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.DatabaseEntity.ArriveDatabase;
import com.yunmang.entity.ExceptionBean;
import com.yunmang.entity.NameBean;
import com.yunmang.entity.ParameterEntity.ConfirmBean;
import com.yunmang.entity.ParameterEntity.UploadConfirmBean;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.ScanUtils;
import com.yunmang.utils.SpeakUtils;
import com.yunmang.utils.ViewHolderUtils;
import com.yunmang.view.WarningDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/9.
 */
public class ArriveActivity extends BaseActivity implements AdapterView.OnItemClickListener, OnItemClickListener {
    @InjectView(R.id.et_search)
    EditText etSearch;
    @InjectView(R.id.iv_scan)
    ImageView ivScan;
    @InjectView(R.id.ll_search)
    LinearLayout llSearch;
    @InjectView(R.id.btn_search)
    Button btnSearch;
    @InjectView(R.id.danhuolistview)
    ListView listview;
    @InjectView(R.id.btn_confirm)
    Button btnConfirm;
    @InjectView(R.id.btn_allSelect)
    Button btnAllSelect;
    @InjectView(R.id.btn_del)
    Button btnDel;
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.ll_container)
    LinearLayout ll_container;
    @InjectView(R.id.cb)
    ImageView cb;
    @InjectView(R.id.tv_settle)
    TextView tvSettle;
    @InjectView(R.id.tv_price)
    TextView tvPrice;
    @InjectView(R.id.tv_order_total)
    TextView tvOrderTotal;
    @InjectView(R.id.tv_order_scannum)
    TextView tvOrderScannum;
    @InjectView(R.id.tv_order_allnum)
    TextView tvOrderAllnum;
    @InjectView(R.id.fab)
    FloatingActionButton fab;
    private Subscriber subScriber;
    private List<ConfirmBean.ModelBean.ItemsBean> dataList;
    private ConfirmAdapter adapter;
    private UploadConfirmBean uploadConfirmBean;
    private List<UploadConfirmBean.BillConfirmItemListBean> subList;
    private AlertView mConfirmAlert, mDelAlert;
    private int totalCount,totalGoodssum,scannum;
    private BigDecimal totalPrice;//总运费
    private String originallhdbh;//原始hdbh
    private ExceptionBean initExceptionGoods;
    private WarningDialog warningDialog;
    private SpeakUtils speak;
    private ScanReceiver scanReceiver=new ScanReceiver();
    @Override
    public int getLayoutId() {
        return R.layout.activity_daohuo_detail;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        initToolbar();
        speak=new SpeakUtils(this);
    }

    @Override
    public void initData() {
//        CommonDaoUtils.getArriveManager().deleteAll(ArriveDatabase.class);
        List<ArriveDatabase> list = CommonDaoUtils.getArriveManager().getAllByDepName(AppConstant.orgInfo.getName());
        dataList=new ArrayList<>();
        if(list!=null){
            for (ArriveDatabase database:list) {
                ConfirmBean.ModelBean.ItemsBean ib=new ConfirmBean.ModelBean.ItemsBean();
                ib.setId(database.getId());
                ib.setHdbh(database.getHdbh());
                ib.setBillDate(database.getBillDate());
                ib.setGoodsName(database.getGoodsName());
                ib.setShipper(database.getShipper());
                ib.setShipperPhone(database.getShipperPhone());
                ib.setConsignee(database.getConsignee());
                ib.setConsigneePhone(database.getConsigneePhone());
                ib.setPack(database.getPack());
                ib.setNumbers(database.getNumbers());
                ib.setBalanceMethod(database.getBalanceMethod());
                ib.setTransportCost(database.getTransportCost());
                ib.setGoodsCost(database.getGoodsCost());
                ib.setWeight(database.getWeight());
                ib.setCubage(database.getCubage());
                ib.setDisplayStatus(database.getDisplayStatus());
                ib.setStartDepartName(database.getStartDepartName());
                ib.setSendDate(database.getSendDate());
                ib.setSaomiaonum(database.getSaomiaonum());
                ib.setBatchBillId(database.getBatchBillId());
                dataList.add(ib);
            }
        }
        adapter=new ConfirmAdapter(this,dataList);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(this);
        calculate();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        ll_container.setVisibility(View.VISIBLE);
    }

    private void getConfirmInfo(String hdbh) {
        showWaitingDialog("加载中……");
        subScriber = new Subscriber<ConfirmBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                hideWaitingDialog();
                showToast("网络连接错误" + e.toString());
            }

            @Override
            public void onNext(ConfirmBean confirmBean) {
                hideWaitingDialog();
                if (confirmBean.getCode() == 200) {
                    dataList = confirmBean.getModel().getItems();
                    if (dataList.size() == 0) {
                        showToast("暂无到货数据");
                        return;
                    }

                    //获取到数据，需要存入到数据库中
                    ScanUtils.operateFile(context,AppConstant.Record_arrive,originallhdbh);
                    List<ArriveDatabase> arriveDatabaseList=new ArrayList<>();
                    for(ConfirmBean.ModelBean.ItemsBean itemsBean:dataList){
                        ArriveDatabase bean=new ArriveDatabase();
                        bean.setId(itemsBean.getId());
                        bean.setBatchBillId(itemsBean.getBatchBillId());
                        bean.setHdbh(itemsBean.getHdbh());
                        bean.setBillDate(itemsBean.getBillDate());
                        bean.setGoodsName(itemsBean.getGoodsName());
                        bean.setShipper(itemsBean.getShipper());
                        bean.setShipperPhone(itemsBean.getShipperPhone());
                        bean.setConsignee(itemsBean.getConsignee());
                        bean.setConsigneePhone(itemsBean.getConsigneePhone());
                        bean.setPack(itemsBean.getPack());
                        bean.setNumbers(itemsBean.getNumbers());
                        bean.setBalanceMethod(itemsBean.getBalanceMethod());
                        bean.setTransportCost(itemsBean.getTransportCost());
                        bean.setGoodsCost(itemsBean.getGoodsCost());
                        bean.setWeight(itemsBean.getWeight());
                        bean.setCubage(itemsBean.getCubage());
                        bean.setDisplayStatus(itemsBean.getDisplayStatus());
                        bean.setStartDepartName(itemsBean.getStartDepartName());
                        bean.setSendDate(itemsBean.getSendDate());
                        bean.setSaomiaonum(itemsBean.getSaomiaonum());
                        bean.setDepName(AppConstant.orgInfo.getName());
                        arriveDatabaseList.add(bean);
                    }
                    for(int i=0;i<dataList.size();i++){
                        String hdbh=dataList.get(i).getHdbh();
                        if(CommonDaoUtils.getArriveManager().isExitThisData(hdbh)){
//                            showToast("存在该单号");
                        }else{//插入数据库中
                            CommonDaoUtils.getArriveManager().insertMultObject(arriveDatabaseList);
                        }
                    }
                        dataList = getAllData();
                        adapter.refreshData(dataList);
                        calculate();
                    if(AppConstant.isAutoUpload_arrive){
                        for(int i=0;i<dataList.size();i++){
                            String hdbh=dataList.get(i).getHdbh();
                            Long id=CommonDaoUtils.getArriveManager().getTableIdByHdbh(hdbh);
                            if(CommonDaoUtils.getArriveManager().getIsUpload(id)){
                                //选中该项，并上传
                                selectOne(i);
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        confirmBillInfo();
                                    }
                                },1000);
                            }
                        }
                    }
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("下载成功");
                } else {
                    showToast("获取数据失败");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("下载失败");
                }
            }
        };
        HttpUtils.getInstance().billConfirm(subScriber, AppConstant.userid, hdbh);
    }

    /**
     * 1.本地库存在，扫描数增加，成功之后记录单号
     * 2.本地库不存在则联网下载
     * 		a.下载成功
     * 		b.下载失败
     * 		处理：下载成功则把单号存起来，否则不记录
     * @param originhdbh
     */
    private void requestData(String originhdbh){
        boolean isfind=false;
        //遍历查找
        for(int i=0;i<dataList.size();i++){
            ConfirmBean.ModelBean.ItemsBean innerBean=dataList.get(i);
            String hdbh=innerBean.getHdbh();
            Long id=CommonDaoUtils.getArriveManager().getTableIdByHdbh(hdbh);
            if(hdbh.equals(originhdbh)){
                isfind=true;
                int num=innerBean.getNumbers();
                int saomiaonum=Integer.parseInt(innerBean.getSaomiaonum());
                if(saomiaonum<num){
                    updateSaomiaonum(innerBean.getHdbh(),String.valueOf(saomiaonum+1));
                    innerBean.setSaomiaonum(String.valueOf(saomiaonum+1));
                    adapter.refreshData(dataList);
                    calculate();
                    //更新数据成功后，扫描单号记录到文件中
                    ScanUtils.operateFile(context,AppConstant.Record_arrive,originallhdbh);
                    if(AppConstant.isAutoUpload_arrive){
                        if(CommonDaoUtils.getArriveManager().getIsUpload(id)){
                            //选中该项，并上传
                            selectOne(i);
                            new Handler().post(new Runnable() {
                                @Override
                                public void run() {
                                    confirmBillInfo();
                                }
                            });
                            break;
                        }
                    }
                }else{
                    showToast("超过货物数量");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("超过货物数量，不能再次扫描");
                }
                break;
            }
        }
        if(isfind==false){
            getConfirmInfo(originhdbh);
        }
    }

    /**
     * 读取数据库中的数据
     */
    private List<ConfirmBean.ModelBean.ItemsBean> getAllData(){
        List<ConfirmBean.ModelBean.ItemsBean> dataList=new ArrayList<>();
        List<ArriveDatabase> arriveDatabases = CommonDaoUtils.getArriveManager().getAllByDepName(AppConstant.orgInfo.getName());
        for (ArriveDatabase bean:arriveDatabases) {
            ConfirmBean.ModelBean.ItemsBean item=new ConfirmBean.ModelBean.ItemsBean();
            item.setId(bean.getId());
            item.setHdbh(bean.getHdbh());
            item.setBillDate(bean.getBillDate());
            item.setGoodsName(bean.getGoodsName());
            item.setShipper(bean.getShipper());
            item.setShipperPhone(bean.getShipperPhone());
            item.setConsignee(bean.getConsignee());
            item.setConsigneePhone(bean.getConsigneePhone());
            item.setPack(bean.getPack());
            item.setNumbers(bean.getNumbers());
            item.setBalanceMethod(bean.getBalanceMethod());
            item.setTransportCost(bean.getTransportCost());
            item.setGoodsCost(bean.getGoodsCost());
            item.setBatchBillId(bean.getBatchBillId());
            item.setWeight(bean.getWeight());
            item.setCubage(bean.getCubage());
            item.setDisplayStatus(bean.getDisplayStatus());
            item.setStartDepartName(bean.getStartDepartName());
            item.setSendDate(bean.getSendDate());
            item.setSaomiaonum(bean.getSaomiaonum());
            dataList.add(item);
        }
        return dataList;
    }
    /**
     * 根据hdbh更新扫描数
     * @param hdbh
     * @param saomiaonum
     */
    private void updateSaomiaonum(String hdbh, String saomiaonum) {
        Long id=CommonDaoUtils.getArriveManager().getTableIdByHdbh(hdbh);
        ArriveDatabase database = CommonDaoUtils.getArriveManager().QueryById(id, ArriveDatabase.class);
        if(database==null){
            showToast("找不到");
            return;
        }
        database.setSaomiaonum(saomiaonum);
        CommonDaoUtils.getArriveManager().updateObject(database);

    }
    @OnClick({R.id.leak,R.id.fab,R.id.tv_settle,R.id.cb,R.id.iv_scan, R.id.btn_search, R.id.btn_confirm, R.id.btn_del, R.id.btn_allSelect})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leak:
                if(dataList.size()>0){
                    initExceptionGoods = ScanUtils.initExceptionGoodsForArrive(dataList);
                    if(initExceptionGoods.getExceptionGoods().size()>0){
                        Intent intent=new Intent(context,LeakageInformation.class);
                        intent.putExtra("Tag",AppConstant.Tag_arrive);
                        intent.putExtra("filename",AppConstant.Record_arrive);
                        intent.putStringArrayListExtra("leakinformation",initExceptionGoods.getExceptionGoods());
                        intent.putStringArrayListExtra("totalNumbers",initExceptionGoods.getTemptotal());
                        startActivity(intent);
                    }else{
                        showAlertDialog("不存在漏扫单号");
                    }
                }else{
                    showAlertDialog("当前列表无数据");
                }
                break;
            case R.id.fab:
                if(dataList.size()>0){
                    setmDelAlert();
                }else{
                    showAlertDialog("当前列表无数据");
                }

                break;
            case R.id.tv_settle://上传需要确认
                if(dataList.size()>0){
                    setmConfirmAlert();
                }else{
                    showAlertDialog("当前列表无数据");
                }
                break;
            case R.id.cb:
                if(dataList.size()>0){
                    cb.setSelected(!cb.isSelected());
                    if (cb.isSelected()) {
                        selectAll();
                    } else {
                        resetState(false);
                    }
                }else{
                    showAlertDialog("当前列表无数据");
                }
                break;
            case R.id.iv_scan:
                CommonUtils.onScanBarcode(this);
                break;
            case R.id.btn_search:
                CommonUtils.hideSoftInput(this);
                String search = CommonUtils.getTextViewValue(etSearch);
                if (TextUtils.isEmpty(search)) {
                    showToast("货单号不能为空");
                    return;
                }
                originallhdbh=search;
//                if(search.length()<12){
//                    if(speak.isSpeeach()){
//                        speak.stopSppach();
//                    }
//                    speak.initParams("单号长度必须大于等于12位");
//                    showToast("单号长度必须大于等于12位");
//                    return;
//                }
                String sub=search.substring(0,originallhdbh.length()-3);
                //先看历史文件中是否存有该单号
                if(!ScanUtils.isExistScanHdbh(context,AppConstant.Record_arrive,originallhdbh)) {
                    requestData(sub);
                }else{
                    showToast("该货物已经扫描过");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("该货物已经扫描过");
                }

                break;
            case R.id.btn_allSelect:
                selectAll();
                break;
            case R.id.btn_del:
                if(dataList.size()>0){
                    deleteSelectedData();
                }else{
                    showAlertDialog("当前列表无数据");
                }
                break;
            case R.id.btn_confirm:
                if(dataList.size()>0){
                    confirmBillInfo();
                }else{
                    showAlertDialog("当前列表无数据");
                }
                break;
        }
    }

    private void confirmBillInfo() {
        uploadConfirmBean = new UploadConfirmBean();
        if (adapter.hasSelected.size() > 0) {

            for (int i = 0; i < dataList.size(); i++) {
                if (adapter.isselect.get(i)) {
                    dataList.get(i).setSelect(true);
                } else {
                    dataList.get(i).setSelect(false);
                }
            }

            if(AppConstant.isAllScan_arrive){
                if(!ScanUtils.isUploadDataForArrive(dataList)){
                    warningDialog = new WarningDialog(this, R.style.Prompt_dialog);
                    if(!warningDialog.isShowing()){
                        warningDialog.show();
                    }
                    return;
                }
            }
            subList = new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                if (adapter.isselect.get(i)) {
                    UploadConfirmBean.BillConfirmItemListBean bean = new UploadConfirmBean.BillConfirmItemListBean();
                    bean.setId(dataList.get(i).getId());
                    bean.setBatchBillId(dataList.get(i).getBatchBillId());
                    subList.add(bean);
                }
            }
            uploadConfirmBean.setUserId(Integer.parseInt(AppConstant.userid));
            uploadConfirmBean.setUserHostAddress("mac地址");
            uploadConfirmBean.setBillConfirmItemList(subList);
            Gson gson = new Gson();
            String body = gson.toJson(uploadConfirmBean);
            uploadConfirm(body);
        } else {
            showToast("请选中要发车的运单");
        }
    }

    /**
     * 确认到货
     *
     * @param body
     */
    private void uploadConfirm(String body) {
        showWaitingDialog("上传数据中……");
        subScriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                showAlertDialog("到货失败");
                if(speak.isSpeeach()){
                    speak.stopSppach();
                }
                speak.initParams("到货失败");
                hideWaitingDialog();
            }

            @Override
            public void onNext(NameBean nameBean) {
                hideWaitingDialog();
                if (nameBean.getCode() == 200) {
                    showToast("上传成功");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("到货成功");
                    //成功之后，需要刷新
                    deleteSelectedData();
                    calculate();
                } else {
                    showToast("上传失败");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("到货失败");
                }
            }
        };
        RequestBody bb = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        HttpUtils.getInstance().uploadConfirm(subScriber, bb);
    }

    private void selectAll() {
        for (int i = 0; i < dataList.size(); i++) {
            adapter.isselect.put(i, true);
            dataList.get(i).setSelect(true);
            adapter.hasSelected.add(String.valueOf(i));
        }
        resetState(true);
    }

    /**
     * 选中某一个选项
     */
    private void selectOne(int position){
        adapter.isselect.put(position,true);
        dataList.get(position).setSelect(true);
        adapter.hasSelected.add(String.valueOf(position));
        adapter.notifyDataSetChanged();
    }
    /**
     * 反选
     */
    private void cancelAll() {
        for (int i = 0; i < dataList.size(); i++) {
            adapter.isselect.put(i, false);
            adapter.hasSelected.clear();
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 删除所有选中的数据
     */
    private void deleteSelectedData() {
        if (adapter.hasSelected.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                if (adapter.isselect.get(i)) {
                    dataList.get(i).setSelect(true);
                } else {
                    dataList.get(i).setSelect(false);
                }
            }
            deletedData(dataList);
            ScanUtils.clearHistoryHdbhforArrive(context,AppConstant.Record_arrive,dataList);
            Iterator<ConfirmBean.ModelBean.ItemsBean> iter = dataList.iterator();
            while (iter.hasNext()) {
                ConfirmBean.ModelBean.ItemsBean next = iter.next();
                if (next.isSelect()) {
                    iter.remove();
                }
            }
            resetState(false);
        } else {
            showToast("请选择要删除的条目");
        }
    }
    /**
     * 将所有选中的封装一个集合
     * @param dataList
     * @return
     */
    private void deletedData(List<ConfirmBean.ModelBean.ItemsBean> dataList){
        for (int i = 0; i < dataList.size(); i++) {
            if(dataList.get(i).isSelect()){
                String hdbh=dataList.get(i).getHdbh();
                Long tableID = CommonDaoUtils.getArriveManager().getTableIdByHdbh(hdbh);
                CommonDaoUtils.getArriveManager().deleteDataByid(tableID);
            }
        }
    }

    /**
     * 重置CheckBox的状态
     * true  清除
     * false 全选
     */
    private void resetState(Boolean SelectAll) {
        {
            if (SelectAll) {
                adapter.setSelectAll(true);
                adapter.isClearAllCheckBox(false);
            } else {
                for (int i = 0; i < dataList.size(); i++) {
                    adapter.isselect.put(i, false);
                }
                adapter.hasSelected.clear();
                adapter.setSelectAll(false);
                adapter.isClearAllCheckBox(true);
                Log.e("del", adapter.hasSelected.size() + "个");
            }
            if(SelectAll){
                adapter.refreshSeletedData(dataList);
            }else{
                adapter.refreshData(dataList);
            }

            calculate();
            Log.e("result", adapter.hasSelected.size() + "个");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        CheckBox cb = ViewHolderUtils.get(view, R.id.cb_choose);
        cb.toggle();
        adapter.isselect.put(i, cb.isChecked());
        if (adapter.hasSelected.contains(String.valueOf(i))) {
            adapter.hasSelected.remove(String.valueOf(i));
        } else {
            adapter.hasSelected.add(String.valueOf(i));
        }
    }

    /**
     * 弹出对话框
     * @param string
     * */
    private void showAlertDialog(String string) {
        new AlertView("提示",string, null,new String[]{"确定"}, null,this,AlertView.Style.Alert,this).show();
    }

    private void setmConfirmAlert() {
        mConfirmAlert = new AlertView("提示", "确定要上传选中的数据", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this);
        mConfirmAlert.setCancelable(true).show();
    }

    private void setmDelAlert() {
        mDelAlert = new AlertView("提示", "确定要删除选中的数据", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this);
        mDelAlert.setCancelable(true).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                etSearch.setText(result.getContents());
//                Toast.makeText(this, "扫描成功，条码值: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == mConfirmAlert && position != AlertView.CANCELPOSITION) {
            confirmBillInfo();
        } else if(o == mDelAlert && position != AlertView.CANCELPOSITION) {
            deleteSelectedData();
        }
    }

    /**
     * 统计所有信息
     */
    private void calculate() {
        totalCount =dataList.size();
        totalGoodssum=0;
        totalPrice=new BigDecimal("0");
        scannum=0;
        for (ConfirmBean.ModelBean.ItemsBean bean:dataList) {
            int num=bean.getNumbers();
            int saomiao=Integer.parseInt(bean.getSaomiaonum());
            Double yf=bean.getTransportCost();
            totalGoodssum+=num;
            BigDecimal bd=new BigDecimal(yf+"");
            totalPrice=totalPrice.add(bd);
            scannum+=saomiao;
        }
        tvPrice.setText("￥" + totalPrice.toString());
        tvOrderTotal.setText(totalCount+"");
        tvOrderAllnum.setText(totalGoodssum+"");
        tvOrderScannum.setText(scannum+"");
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.android.server.scannerservice.broadcast");
        filter.addAction("android.intent.action.SCANRESULT");
        registerReceiver(scanReceiver,filter);
//        registerReceiver(scanReceiver,new IntentFilter("com.android.server.scannerservice.broadcast"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(scanReceiver);
    }

    private class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.android.server.scannerservice.broadcast")){
                originallhdbh=intent.getStringExtra("scannerdata").trim();
            }else if(intent.getAction().equals("android.intent.action.SCANRESULT")){
                originallhdbh=intent.getStringExtra("value").trim();
            }
                etSearch.setText(originallhdbh);
//                if(originallhdbh.length()<12){
//                    if(speak.isSpeeach()){
//                        speak.stopSppach();
//                    }
//                    speak.initParams("单号长度必须大于等于12位");
//                    showToast("单号长度必须大于等于12位");
//                    return;
//                }
                String sub=originallhdbh.substring(0,originallhdbh.length()-3);
                //先看历史文件中是否存有该单号
                if(!ScanUtils.isExistScanHdbh(context,AppConstant.Record_arrive,originallhdbh)) {
                    requestData(sub);
                }else{
                    showToast("该货物已经扫描过");
                    if(speak.isSpeeach()){
                        speak.stopSppach();
                    }
                    speak.initParams("该货物已经扫描过");
                }
            }
    }
}
